"""
python-gitlab API文档：https://python-gitlab.readthedocs.io/en/v3.3.0/gl_objects/branches.html
"""

import gitlab
from rest_framework import viewsets, response
import threading
from utils.views import FsLog
import time

# from app01.log import LogInterface
# from app01.webhook import FeiShuWebHook
# from utils.views import FeiShu_WebHook

# gl = gitlab.Gitlab(url="http://gitlab.test.ihomecloud.cn/",private_token='glpat-fJq6ugNWqxvnUQW8ouJP')
# gl = gitlab.Gitlab(url="http://gitlab.test.ihomecloud.cn/",oauth_token='glpat-4BKDNLYbyo4UtS2fnby3')
# gl = gitlab.Gitlab(url="http://gitlab.test.ihomecloud.cn/",private_token='glpat-xA7kMnoyabKLu6ZwzJdb')

# ## gitlab.test.ihomecloud.cn环境的aihma-cloud管理token
# gl = gitlab.Gitlab(url="http://gitlab.test.ihomecloud.cn/",oauth_token='glpat-xA7kMnoyabKLu6ZwzJdb')

## gitlab.test.ihomecloud.cn环境的aihma-cloud管理token
# gl = gitlab.Gitlab(url="http://git.bsphpro.com", oauth_token='glpat-WeTwtaG4ifaHPYwwUvC9',per_page=100)

## gitlab.test.ihomecloud.cn环境的aihma-cloud管理token
# gl = gitlab.Gitlab(url="http://gitlab.edccmss.cn", oauth_token='glpat-BsE4H3vGpkd17aDxG8ZK',per_page=100)


## 后端 gitlab_token
class GL:
    def __init__(self):
        self.url = "https://gitlab.edccmss.cn"
        self.token = "glpat-BsE4H3vGpkd17aDxG8ZK"
        self.per_page = 100



    def gl(self):
        gl = gitlab.Gitlab(url=self.url, oauth_token=self.token, per_page=self.per_page)
        return gl


## 后端 GitLab 管理接口
class GitLabManager(viewsets.ViewSet,
                 viewsets.mixins.ListModelMixin,
                 viewsets.mixins.CreateModelMixin,
                 viewsets.mixins.RetrieveModelMixin,
                 viewsets.mixins.DestroyModelMixin,
                 ):



    def retrieve(self, request, *args, **kwargs):
        # print('进来这里了2')

        url = request.path.split('/')
        g = GL()

        ##  创建分支
        if 'CreateBranch' in url:
            srcbranch = request.GET.get("srcbranch")
            destbranch = request.GET.get("destbranch")

            eat_thread = threading.Thread(target=self.CreateBranchs,
                                          kwargs={"gitlab_client": g, "src_br": srcbranch, "dest_br": destbranch,
                                                  "Group": "aihma-cloud"},
                                          daemon=True)
            eat_thread.start()

            return response.Response({'type': 'success', 'msg': '创建分支：%s 成功' % destbranch})

        ##  删除分支
        if 'DeleteBranch' in url:
            BranchName = request.GET.get("BranchName")

            eat_thread = threading.Thread(target=self.DelBranchs, kwargs={"gitlab_client": g, "BranchName": BranchName, "Group": "aihma-cloud"}, daemon=True)
            eat_thread.start()

            return response.Response({'type': 'success', 'msg': '删除分支：%s 任务已提交' % BranchName})

        ## 合并分支
        if 'MergeBranch' in url:
            srcbranch = request.GET.get("srcbranch")
            destbranch = request.GET.get("destbranch")

            eat_thread = threading.Thread(target=self.megres,
                                          kwargs={"gitlab_client": g, "src_br": srcbranch, "dest_br": destbranch, "Group": "aihma-cloud"},
                                          daemon=True)
            eat_thread.start()

            return response.Response({'type': 'success', 'msg': '合并任务提交完成'})

        return response.Response({'type': 'success', 'msg': '没有做任何操作'})


    def CreateBranch(self,gitlab_client, project, srcbranch, destbranch):
        # T = Tlog()
        try:
            gitlab_client.gl().CreateBranch(project, srcbranch, destbranch)
            # LogInterface.Build_Log.save_build("项目：%s 分支：%s 创建成功~~" % (project.name, destbranch))
            # T.info("项目：%s 分支：%s 创建成功~~" % (project.name, destbranch), type='gitlab', dbname='gitlab')
            FsLog("项目：%s 分支：%s 创建成功！！" % (project.name, destbranch))
        except Exception as e:
            FsLog("项目：%s 分支：%s 创建失败，原因：%s" % (project.name, destbranch, e))
            # LogInterface.Build_Log.save_build("项目：%s 分支：%s 创建失败，原因：%s" % (project.name, destbranch, e))
            # T.error("项目：%s 分支：%s 创建失败，原因：%s" % (project.name, destbranch, e), type='gitlab', dbname='gitlab')
            # print(2,e)

    def DeleteBranch(self, gitlab_client, BranchName, project):
        # T = Tlog()
        try:
            gitlab_client.gl().DeleteBranch(project, BranchName)
            # FsLog("项目：%s 分支：%s 删除成功~~" % (project.name, BranchName))
            # LogInterface.Build_Log.save_build("项目：%s 分支：%s 删除成功~~" % (project.name, BranchName))
        except Exception as e:
            FsLog("项目：%s 分支：%s 删除失败，失败原因：%s" % (project.name, BranchName, e))
            # LogInterface.Build_Log.save_build("项目：%s 分支：%s 删除失败，失败原因：%s" % (project.name, BranchName, e))
            # T.error("项目：%s 分支：%s 删除失败，失败原因：%s" % (project.name, BranchName, e), type='gitlab', dbname='gitlab')

    ## 合并分支（后端）
    def megre(self, project, src_br, dest_br):
        # T = Tlog()
        ## 检查已有的合并请求
        merge_cu = [{"msg": "当前存在开启状态的合并请求，请先检查！"}, {"flg": []}]
        mrs = project.mergerequests.list(state='opened', order_by='updated_at')
        # print("项目：%s   打开的合并请求：%s" %(project.name,mrs))
        if mrs:
            # for mr in mrs:
            # merge_cu.append(project.name)
            merge_cu[1]["flg"].append(project.name)
        if merge_cu[1]["flg"]:
            # return "当前存在未开启状态的合并请求，请先检查！",merge_cu
            FsLog("当前存在未开启状态的合并请求，请先检查！，%s\n" % merge_cu)
            # qwLog("当前存在未开启状态的合并请求，请先检查！，%s\n" % merge_cu)

            return {'type': 'error', "msg": "当前存在开启状态的合并请求，请先检查！"}

        ## 创建合并请求
        try:
            mr = project.mergerequests.create({'source_branch': '%s' % src_br,
                                               'target_branch': '%s' % dest_br,
                                               'title': 'merge %s to %s' % (src_br, dest_br),
                                               'labels': ['from_pythonAPI']})
            # FsLog("项目：%s 创建megre成功\n" % (project.name))
            # print("项目：%s 创建megre成功" % (project.name))
            # T.info("项目：%s 创建megre成功" % (project.name), type='gitlab', dbname='gitlab')
        except Exception as e:
            # FsLog("项目：%s 创建merge失败，失败原因：%s\n" % (project.name, e))
            print("项目：%s 创建merge失败，失败原因：%s" % (project.name, e))
            # T.error("项目：%s 创建merge失败，失败原因：%s" % (project.name, e), type='gitlab', dbname='gitlab')

        ## 检查已有的合并请求
        mrs = project.mergerequests.list(state='opened', order_by='updated_at')

        time.sleep(4)
        ## 合并
        merge_ok = [{"msg": "合并完成！"}, {"flg": []}]
        if mrs:
            for mr in mrs:
                try:
                    mr.merge()
                    merge_ok[1]["flg"].append(mr.references["full"])
                    # LogInterface.Build_Log.save_build("合并成功，项目：%s  merge_iid：%s " % (mr.references["full"], mr.iid))
                    FsLog("合并成功，项目：%s  merge_iid：%s " % (mr.references["full"], mr.iid))
                    # T.info("合并成功，项目：%s  merge_iid：%s " % (mr.references["full"], mr.iid), type='gitlab', dbname='gitlab')
                    print("合并成功，项目：%s  merge_iid：%s " % (mr.references["full"], mr.iid))
                except Exception as e:
                    # LogInterface.Build_Log.save_build("合并失败，项目：%s  merge_iid：%s 失败原因：%s" % (mr.references["full"], mr.iid, e))
                    # T.error("合并失败，项目：%s  merge_iid：%s 失败原因：%s\n" % (mr.references["full"], mr.iid, e), type='gitlab', dbname='gitlab')
                    FsLog("合并失败，项目：%s  merge_iid：%s 失败原因：%s\n" % (mr.references["full"], mr.iid, e))
                    # print("合并失败，项目：%s  merge_iid：%s 失败原因：%s" % (mr.references["full"], mr.iid, e))
                    try:
                        mr.state_event = 'close'
                        mr.save()
                        # FsLog("关闭合并成功，项目：%s  merge_iid：%s " % (mr.references["full"], mr.iid))
                        print("关闭合并成功，项目：%s  merge_iid：%s " % (mr.references["full"], mr.iid))
                    except Exception as f:
                        FsLog("项目：%s  关闭失败  mrid：%s   关闭错误信息：%s" % (mr.references["full"], mr.iid, f))
                        # print("项目：%s  关闭失败  mrid：%s   关闭错误信息：%s" % (mr.references["full"], mr.iid, f))
                        # T.error("项目：%s  关闭失败  mrid：%s   关闭错误信息：%s" % (mr.references["full"], mr.iid, f), type='gitlab', dbname='gitlab')
                        pass
        # print(merge_ok)
        return merge_ok

    ## 多线程创建分支
    def CreateBranchs(self, gitlab_client, src_br, dest_br, Group):
        projects = gitlab_client.gl().GetProjects(group=Group)
        for project in projects:
            self.CreateBranch(gitlab_client, project, src_br, dest_br)

    ## 多线程删除
    def DelBranchs(self, gitlab_client, BranchName, Group):
        projects = gitlab_client.gl().GetProjects(group=Group)

        for project in projects:
            self.DeleteBranch(gitlab_client, BranchName, project)

    ## 多线程合并
    def megres(self, gitlab_client, src_br, dest_br, Group):
        projects = gitlab_client.gl().GetProjects(group=Group)

        for project in projects:
            ## 遍历合并
            self.megre(project, src_br, dest_br)

            ##  多线程合并
            # eat_thread = threading.Thread(target=self.megre,
            #                               kwargs={"project": project, "src_br": src_br, "dest_br": dest_br},
            #                               daemon=True)
            # eat_thread.start()


#
# ## 前端的 Gitlab_token
# def glq():
#     # gl = gitlabApi.GitlabManage(url="http://git.bsphpro.com", oauth_token='glpat-WeTwtaG4ifaHPYwwUvC9',per_page=100)
#     glq = gitlabApi.GitlabManage(url="http://git.bsphpro.com", oauth_token='glpat-17yHK2BDqX2g3P-oF9Mk', per_page=100)
#     return glq
#
# ## 前端 GitLab 管理接口
# class GitLabManagerQ(viewsets.ViewSet,
#                  viewsets.mixins.ListModelMixin,
#                  viewsets.mixins.CreateModelMixin,
#                  viewsets.mixins.RetrieveModelMixin,
#                  viewsets.mixins.DestroyModelMixin,
#                  ):
#
#     def retrieve(self, request, *args, **kwargs):
#         print('进来这里了3')
#         url = request.path.split('/')
#         gl = glq()
#
#         ##  创建分支
#         if 'CreateBranch' in url:
#             srcbranch = request.GET.get("srcbranch")
#             destbranch = request.GET.get("destbranch")
#
#             eat_thread = threading.Thread(target=self.CreateBranchs,
#                                           kwargs={"gitlab_client": gl, "src_br": srcbranch, "dest_br": destbranch,
#                                                   "Group": "aihma-cloud"},
#                                           daemon=True)
#             eat_thread.start()
#
#             return response.Response({'type': 'success', 'msg': '创建分支：%s 成功' % destbranch})
#
#         ##  删除分支
#         if 'DeleteBranch' in url:
#             BranchName = request.GET.get("BranchName")
#
#             eat_thread = threading.Thread(target=self.DelBranchs, kwargs={"gitlab_client": gl, "BranchName": BranchName, "Group": "aihma-cloud"}, daemon=True)
#             eat_thread.start()
#
#             return response.Response({'type': 'success', 'msg': '删除分支：%s 任务已提交' % BranchName})
#
#         ## 合并分支
#         if 'MergeBranch' in url:
#             srcbranch = request.GET.get("srcbranch")
#             destbranch = request.GET.get("destbranch")
#
#             eat_thread = threading.Thread(target=self.megres,
#                                           kwargs={"gitlab_client": gl, "src_br": srcbranch, "dest_br": destbranch, "Group": "aihma-cloud"},
#                                           daemon=True)
#             eat_thread.start()
#
#             return response.Response({'type': 'success', 'msg': '合并任务提交完成'})
#
#         return response.Response({'type': 'success', 'msg': '没有做任何操作'})
#
#
#     def CreateBranch(self,gitlab_client, project, srcbranch, destbranch):
#         T = Tlog()
#         try:
#             gitlab_client.CreateBranch(project, srcbranch, destbranch)
#             # LogInterface.Build_Log.save_build("项目：%s 分支：%s 创建成功~~" % (project.name, destbranch))
#             T.info("项目：%s 分支：%s 创建成功~~" % (project.name, destbranch), type='gitlab', dbname='gitlab')
#             print('yayayaaya')
#             # FsLog("项目：%s 分支：%s 创建成功！！" % (project.name, destbranch))
#         except Exception as e:
#             # FsLog("项目：%s 分支：%s 创建失败，原因：%s" % (project.name, destbranch, e))
#             # LogInterface.Build_Log.save_build("项目：%s 分支：%s 创建失败，原因：%s" % (project.name, destbranch, e))
#             T.error("项目：%s 分支：%s 创建失败，原因：%s" % (project.name, destbranch, e), 'gitlab', dbname='gitlab')
#             print(f"项目：%s 分支：%s 创建失败，原因：%s" % (project.name, destbranch, e))
#             print('bababab')
#
#     def DeleteBranch(self, gitlab_client, BranchName, project):
#         T = Tlog()
#         try:
#             gitlab_client.DeleteBranch(project, BranchName)
#             # FsLog("项目：%s 分支：%s 删除成功~~" % (project.name, BranchName))
#             # LogInterface.Build_Log.save_build("项目：%s 分支：%s 删除成功~~" % (project.name, BranchName))
#             T.info("项目：%s 分支：%s 删除失败，失败原因：%s" % (project.name, BranchName, e), 'gitlab', dbname='gitlab')
#         except Exception as e:
#             # FsLog("项目：%s 分支：%s 删除失败，失败原因：%s" % (project.name, BranchName, e))
#             # LogInterface.Build_Log.save_build("项目：%s 分支：%s 删除失败，失败原因：%s" % (project.name, BranchName, e))
#             T.error("项目：%s 分支：%s 删除失败，失败原因：%s" % (project.name, BranchName, e), 'gitlab', dbname='gitlab')
#
#     ## 合并分支（前端）
#     def megre(self, project, src_br, dest_br):
#         T = Tlog()
#         ## 检查已有的合并请求
#         merge_cu = [{"msg": "当前存在开启状态的合并请求，请先检查！"}, {"flg": []}]
#         mrs = project.mergerequests.list(state='opened', order_by='updated_at')
#         # print("项目：%s   打开的合并请求：%s" %(project.name,mrs))
#         if mrs:
#             # for mr in mrs:
#             # merge_cu.append(project.name)
#             merge_cu[1]["flg"].append(project.name)
#         if merge_cu[1]["flg"]:
#             # return "当前存在未开启状态的合并请求，请先检查！",merge_cu
#             FsLog("当前存在未开启状态的合并请求，请先检查！，%s\n" % merge_cu)
#             qwLog("当前存在未开启状态的合并请求，请先检查！，%s\n" % merge_cu)
#
#             return {'type': 'error', "msg": "当前存在开启状态的合并请求，请先检查！"}
#
#         ## 创建合并请求
#         try:
#             mr = project.mergerequests.create({'source_branch': '%s' % src_br,
#                                                'target_branch': '%s' % dest_br,
#                                                'title': 'merge %s to %s' % (src_br, dest_br),
#                                                'labels': ['from_pythonAPI']})
#             # FsLog("项目：%s 创建megre成功\n" % (project.name))
#             T.info("项目：%s 创建megre成功" % (project.name), 'gitlab')
#             print("项目：%s 创建megre成功" % (project.name))
#         except Exception as e:
#             # FsLog("项目：%s 创建merge失败，失败原因：%s\n" % (project.name, e))
#             T.error("项目：%s 创建merge失败，失败原因：%s\n" % (project.name, e), 'gitlab')
#             print("项目：%s 创建merge失败，失败原因：%s" % (project.name, e))
#
#         ## 检查已有的合并请求
#         mrs = project.mergerequests.list(state='opened', order_by='updated_at')
#
#         time.sleep(4)
#         ## 合并
#         merge_ok = [{"msg": "合并完成！"}, {"flg": []}]
#         if mrs:
#             for mr in mrs:
#                 try:
#                     mr.merge()
#                     merge_ok[1]["flg"].append(mr.references["full"])
#                     # LogInterface.Build_Log.save_build("合并成功，项目：%s  merge_iid：%s " % (mr.references["full"], mr.iid))
#                     FsLog("合并成功，项目：%s  merge_iid：%s " % (mr.references["full"], mr.iid))
#                     qwLog("合并成功，项目：%s  merge_iid：%s " % (mr.references["full"], mr.iid))
#                     T.info("合并成功，项目：%s  merge_iid：%s " % (mr.references["full"], mr.iid), 'gitlab')
#                     print("合并成功，项目：%s  merge_iid：%s " % (mr.references["full"], mr.iid))
#                 except Exception as e:
#                     LogInterface.Build_Log.save_build("合并失败，项目：%s  merge_iid：%s 失败原因：%s" % (mr.references["full"], mr.iid, e))
#                     T.error("合并失败，项目：%s  merge_iid：%s 失败原因：%s" % (mr.references["full"], mr.iid, e), 'gitlab')
#                     # FsLog("合并失败，项目：%s  merge_iid：%s 失败原因：%s\n" % (mr.references["full"], mr.iid, e))
#                     # print("合并失败，项目：%s  merge_iid：%s 失败原因：%s" % (mr.references["full"], mr.iid, e))
#                     try:
#                         mr.state_event = 'close'
#                         mr.save()
#                         # FsLog("关闭合并成功，项目：%s  merge_iid：%s " % (mr.references["full"], mr.iid))
#                         print("关闭合并成功，项目：%s  merge_iid：%s " % (mr.references["full"], mr.iid))
#                     except Exception as f:
#                         FsLog("项目：%s  关闭失败  mrid：%s   关闭错误信息：%s" % (mr.references["full"], mr.iid, f))
#                         qwLog("项目：%s  关闭失败  mrid：%s   关闭错误信息：%s" % (mr.references["full"], mr.iid, f))
#                         T.error("项目：%s  关闭失败  mrid：%s   关闭错误信息：%s" % (mr.references["full"], mr.iid, f), 'gitlab')
#                         # print("项目：%s  关闭失败  mrid：%s   关闭错误信息：%s" % (mr.references["full"], mr.iid, f))
#                         pass
#         # print(merge_ok)
#         return merge_ok
#
#     ## 多线程创建分支
#     def CreateBranchs(self, gitlab_client, src_br, dest_br, Group):
#         ProjectID_List = [229, 262]
#         projects = gitlab_client.Get_Projects(ProjectID_List)
#         # print('sdsdsd', projects)
#
#         for project in projects:
#             self.CreateBranch(gitlab_client, project, src_br, dest_br)
#
#     ## 多线程删除
#     def DelBranchs(self, gitlab_client, BranchName, Group):
#         ProjectID_List = [229, 262]
#         projects = gitlab_client.Get_Projects(ProjectID_List)
#
#         for project in projects:
#             self.DeleteBranch(gitlab_client, BranchName, project)
#
#     ## 多线程合并
#     def megres(self, gitlab_client, src_br, dest_br, Group):
#         ProjectID_List = [229, 262]
#         projects = gitlab_client.Get_Projects(ProjectID_List)
#
#         for project in projects:
#             ## 遍历合并
#             self.megre(project, src_br, dest_br)
#
#             ##  多线程合并
#             # eat_thread = threading.Thread(target=self.megre,
#             #                               kwargs={"project": project, "src_br": src_br, "dest_br": dest_br},
#             #                               daemon=True)
#             # eat_thread.start()














